// index.js
const db = wx.cloud.database();

Page({
  data: {
    q_id: "1",
    name: "",
    questions: [],
    ans: [],
    openid:null,
    windowHeight: 0,
    windowWidth: 0
  },

  getOpenId(){
    const that = this;
    wx.cloud.callFunction({
      // 云函数名称
      name: 'getOpenId',
    })
    .then(res => {
      that.setData({
        openid:res.result.openid
      })
    })
    .catch(console.error)
  },

  onTextInput(event) {
    console.log(event)
    const qId = event.target.dataset.qid;
    const qType = event.target.dataset.qtype;
    const text = event.detail.value;

    const newAnswer = {
      "id": qId,
      "type": qType,
      "text": text,
    }

    this._addAnswer(newAnswer);
  },

  _addAnswer(newAnswer) {
    let tmpAnswers = this.data.ans;
    const foundIndex = tmpAnswers.findIndex((item) => {
      return item.id == newAnswer.id;
    });
    if (foundIndex !== -1) {
      tmpAnswers.splice(foundIndex, 1, newAnswer);
    } else {
      tmpAnswers = [...tmpAnswers, newAnswer];
    }

    this.setData({
      ans: tmpAnswers,
    })
  },

  _addVoidAnswer(newAnswer) {
    let tmpAnswers = this.data.ans;
    const foundIndex = tmpAnswers.findIndex((item) => {
      return item.id == newAnswer.id;
    });
    console.log(tmpAnswers);
    console.log("found!!")
    console.log(foundIndex)
    if (foundIndex == -1) {
      tmpAnswers = [...tmpAnswers, newAnswer];
      console.log(tmpAnswers);
    } 
    else{
      return;
    }
    this.setData({
      ans: tmpAnswers,
    })
  },

  onReady: function () {
    wx.getSystemInfo({
      success: res => {
        this.setData({
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight
        })
      }
    })
  },

  onRadioChange(event) {
    // console.log(event)
    console.log(event)
    const qId = event.target.dataset.qid;
    const qType = event.target.dataset.qtype;
    const optionId = event.detail.value;
    console.log(this.data.questions);
    const tmpQ = this.data.questions.find((item) => {
      return item.id == qId;
    })

    console.log(tmpQ);

    const tmpOption = tmpQ.options.find((item) => {
      return item.option_id == optionId
    })
    // console.log(tmpOption)

    const newAnswer = {
      "id": qId,
      "type": qType,
      "options": [{
        "option_id": optionId,
        "option_value": tmpOption.option_value,
      }]
    }

    this._addAnswer(newAnswer);

  },
  onCheckboxChange(event) {
    //console.log(event)
    const qId = event.target.dataset.qid;
    const qType = event.target.dataset.qtype;
    const arrSelectedValue = event.detail.value;


    const tmpQ = this.data.questions.find((item) => {
      return item.id == qId;
    })

    let tmpAnswerOptions = [];
    arrSelectedValue.forEach(optionId => {
      let tmpOption = tmpQ.options.find(item => {
        return item.option_id == optionId;
      })
      if (tmpOption) {
        tmpAnswerOptions.push({
          "option_id": tmpOption.option_id,
          "option_value": tmpOption.option_value,
        })
      }
    })

    tmpAnswerOptions.sort((a, b) => {
      return a.option_id > b.option_id ? 1 : -1;
    })

    const newAnswer = {
      id: qId,
      type: qType,
      options: tmpAnswerOptions,
    }

    this._addAnswer(newAnswer)

  },

  getQuestion(q_id) {
    const that = this;

    wx.cloud.callFunction({
      name:'getQuestion',
      data:{
        q_id:q_id
      }
    })
    .then(res =>{
      console.log(res);
      if(res.result.errmsg == 'OK'){
        that.setData({
          name:res.result.data.name,
          questions:res.result.data.questions, 
        })
      }else{
        wx.showToast({
          title: '查询题目失败',
          icon:"error",
        })
      }
    })
    .catch(err => {
           console.error(err)
       })
  },
  submitAnswer() {
    
    const that = this;
    const q_id = this.data.q_id;
    console.log("????????????")
    console.log(this.data.ans);
    for(var j = 0;j<this.data.questions.length;j++)
    {
      this._addVoidAnswer({
        "id": j+1,
      })
    }
    const ans = this.data.ans.sort((a, b) => {
      return a.id - b.id;
    });
    console.log("????????????")
    console.log(ans);

    const objAnswer = {
      q_id:q_id,
      ans: ans,
    }
    
    wx.cloud.callFunction({
      name:'submitAnswer',
      data:{
        objAnswer:objAnswer
      }
    })
    .then(res=>{
      console.log(res);
      if(res.result.errcode == 0){
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000
        })
        wx.reLaunch({
          url: '../index/index'
        }) 
      }else{
        wx.showToast({
          title: '保存失败',
          icon: 'error',
          duration: 2000
        })  
      }
    })
    .catch(err=>{
      console.error(err);
    })
  },
  // submitAnswer() {
    // const that = this;

    // const q_id = this.data.q_id;
    // const ans = this.data.ans.sort((a, b) => {
    //   return a.id - b.id;
    // });

    // const objAnswer = {
    //   q_id:q_id,
    //   ans: ans,
    // }

  //   db.collection('answers')
  //     .doc(that.data.openid)
  //     .set({
  //       data: objAnswer,
  //     })
  //     .then((res)=>{
  //       //console.log(res)
  //       if(res.errMsg == "document.set:ok"){
  //         wx.showToast({
  //           title: '保存成功',
  //           icon: 'success',
  //           duration: 2000
  //         })
  //       }else{

  //         wx.showToast({
  //           title: '保存失败',
  //           icon: 'error',
  //           duration: 2000
  //         })          
  //       }
  //     })
  //     .catch(err=>{
  //       console.error(err);

  //       wx.showToast({
  //         title: '保存失败',
  //         icon: 'error',
  //         duration: 2000
  //       })      
  //     })

  // },
  onLoad(options) {
    if(options!=null&&options.scene!=null)
    {
      const scene = decodeURIComponent(options.scene);
      console.log(scene);
      console.log("onLoad!")
      this.getQuestion(scene);
      this.setData({
        q_id: scene,
      })
    }
    else{
      this.getOpenId();
      this.getQuestion(this.data.q_id);
    }
  },
});